package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 *
 */
public class RequestProcessor extends Thread {

  private Socket socket;
//  private Map<String, HttpServlet> servletMap = new HashMap<>();
  private Map<String, List<Wrapper>> servletMap;

  public RequestProcessor(Socket socket, Map<String, List<Wrapper>> servletMap) {
    this.socket = socket;
    this.servletMap = servletMap;
  }

  @Override
  public void run() {
    try {
      InputStream inputStream = socket.getInputStream();
      OutputStream outputStream = socket.getOutputStream();
      Request request = new Request(inputStream);
      Response response = new Response(outputStream);
      List<Wrapper> wrapperList = servletMap.get(request.getContextPath());
      if (wrapperList == null) {
        response.outputHtml(request.getUrl());
      } else {
        Optional<Wrapper> any = wrapperList.stream().findAny();
        boolean present = any.isPresent();
        if (!present) {
          response.outputHtml(request.getUrl());
        } else {
          Wrapper wrapper = any.get();
          wrapper.getServlet().service(request, response);
        }
//        HttpServlet httpServlet = (HttpServlet) wrappers;
//        httpServlet.service(request, response);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
